library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;
use ieee.std_logic_arith.all;

entity data_merge2 is
port(
--clk:in std_logic;--100hz
state_save:in integer range 0 to 4;
sech_save,secl_save:in std_logic_vector(7 downto 0);
save_flag:in std_logic;
--data_ram:out std_logic_vector(7 downto 0);
--wren:out std_logic;
--wraddress:out std_logic_vector(4 downto 0)
ram_out0,ram_out1,ram_out2,ram_out3,ram_out4,ram_out5,ram_out6,ram_out7,ram_out8:out std_logic_vector(7 downto 0)
);
end data_merge2;

architecture behav of data_merge2 is
type data_merge is array(0 to 8) of std_logic_vector(7 downto 0);
signal data_temp:data_merge;
signal	cnt:integer range 0 to 2;
signal once_flag:std_logic;
--signal wraddress_temp:std_logic_vector(4 downto 0);
--signal save_flag:std_logic;

begin 
--wren<='1';

process(cnt,save_flag)
--variable save_flag:std_logic;
--variable flag0,flag1,flag2:std_logic;
begin
	--if(save_flag='0') then
	--if(clk'event and clk='1') then
	if(save_flag'event and save_flag='1') then
	--if(save_flag='1') then
		if(cnt=2) then 
		cnt<=0;once_flag<='0';
		else
		cnt<=cnt+1;once_flag<='0';
		end if;
   -- end if;
    
	case cnt is 
	when 0=>
	if(once_flag='0') then
	data_temp(0)<=sech_save;
	data_temp(1)<=secl_save;
	data_temp(2)<=conv_std_logic_vector(state_save,8);
	once_flag<='1';
	end if;
	--data_temp(2)<=conv_std_logic_vector(state_save,8);
	
	when 1=>
	if(once_flag='0') then
	data_temp(3)<=sech_save;
	data_temp(4)<=secl_save;
	data_temp(5)<=conv_std_logic_vector(state_save,8);
	once_flag<='1';
	end if;
	--data_temp(5)<=conv_std_logic_vector(state_save,8);
	
	when 2=>
	if(once_flag='0') then
	data_temp(6)<=sech_save;
	data_temp(7)<=secl_save;
	data_temp(8)<=conv_std_logic_vector(state_save,8);
	once_flag<='1';
	end if;
	--data_temp(8)<=conv_std_logic_vector(state_save,8);
	
	end case;
	
	end if;
	
	--save_flag:=1;
	--end if;
end process;

--process(save_flag)
--begin 
--if(save_flag'event and save_flag='1') then
	--if(cnt=2) then 
	--cnt<=0;once_flag<='0';
	--else
	--cnt<=cnt+1;once_flag<='0';
	--end if;
--end if;
--end process;

ram_out0<=data_temp(0);
ram_out1<=data_temp(1);
ram_out2<=data_temp(2);
ram_out3<=data_temp(3);
ram_out4<=data_temp(4);
ram_out5<=data_temp(5);
ram_out6<=data_temp(6);
ram_out7<=data_temp(7);
ram_out8<=data_temp(8);
--process(data_temp,cnt)
--variable init:std_logic;
--begin 
	--if (data_temp'event) then
	--if(init='0') then
		--wraddress_temp<="00000";init:='1';
	--else
		--case cnt is
			--when 0=>data_ram<=data_temp(0);wraddress_temp<=wraddress_temp+1;--output time
			--when 1=>data_ram<=data_temp(1);wraddress_temp<=wraddress_temp+1;
			--when 2=>data_ram<=data_temp(2);wraddress_temp<=wraddress_temp+1;
		--end case;
	--end if;
	--end if;
--end process;
--wraddress<=wraddress_temp;

end behav;